import './presetVar'
import React, { Component } from 'react';
import { createPage, base, high,promptBox } from 'nc-lightapp-front';
import { refreshButtonClick, tableButtonClick, pageButtonClick, beforeEvent,afterEvent ,invoiceEvent} from './events';
import initTemplate, { routeChange } from './initTemplate';

import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTable,
    CardTableGroup,
    ButtonGroup,
    MultiButtonGroup
} from 'src/erm/sscrppublic/common/components/bill';
//引入侧边栏
import AuditSidebar from 'sscia/auditSidebar/components/auditSidebar'
import './index.less';
import LinkQueryJkbxModel from 'src/erm/sscrppublic/common/linkquery/LinkQueryJkbxModel';
import requestApi from "../../expenseaccount/card/requestApi";
import pubMessage from 'src/erm/sscrppublic/common/utils/pubMessage';
import getAttachmentLength from '../../../public/components/linkAttachment/getAttachmentLength'
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import attachments from 'uap/common/components/getAttachmentInfo';
import ApprovalTrans from 'uap/common/components/approvalTrans';

const { getAttachments, getAttachmentsInfo } = attachments;

const pageButton = window.presetVar.pageButton;
window.assingUsers = [];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk
/**
 * 还款单
 */
class repaymentBillCard extends Component {
    actionByHashChange = false;
    
    constructor(props) {
        super();
          //初始化侧边栏
        this.auditSidebar = new AuditSidebar();
        this.state = {
            billId : '',
            showLinkQueryJkbxModel: false,
            target: null,
            showUploader: false,
            uploadPk : '',
            sourceData: null,
            showLinkBudget: false,
            hideTables:[],
            ShowApproveDetail: false,
            billtype: '',
            linkData:'',
			transtype_name:'',
            compositedata : '',
            compositedisplay : '',
            uploaderBtnDisable: false,
            djzt:'0',
            showAuditSidebar:false,
        }

        initTemplate.call(this, props);
        this.pubMessage = new pubMessage(props);

        props.use.form('head');
    }
    billInvalid(){
        let param = {};
        param.openbillid=this.props.getUrlParam("id")||this.props.getUrlParam("billid");
        param.tradetype=window.presetVar.tradetype;
        param.pagecode=this.props.getSearchParam("p");
        requestApi.billInvalid({
            data: param,
            success: (data) => {
                if (data.success) {
                    location.reload();
                }
            }
        });
    }
    componentWillMount() {
        window.onbeforeunload = () => {
            let status = this.props.getUrlParam("status");
            let addType = this.props.getUrlParam('addtype');

            if (addType != "pull" && (status == 'edit' || status == 'add')) {
                return ''/* 国际化处理： 确定要离开吗？*/
            }
        }
    }
    componentDidMount(){
        this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
        })
    }
    cancel(){
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info){
        this.setState({
            showLinkBudget: false
        })
    }
    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }   
    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        pageButtonClick.call(this)[pageButton.billSubmit]();
        window.assignBillId = '';
        window.sureAssign = false;
    }

    turnOff(){
        window.presetVar.fromBtn = 'turnOff'
        this.setState({
            compositedisplay:false
        }) ;
        window.sureAssign = false;
        let props = this.props;
        props.go({
            status: 'browse',
            id: window.assignBillId,
            tradetype:window.presetVar.tradetype,
            scene:this.props.getUrlParam('scene')
        });
    }
    onHideUploader = () => {
        this.setState({
            showUploader: false,
        });
        let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
        let multiLang = this.props.MutiInit.getIntl(2011);
        getAttachmentLength(id).then(lists => {
            this.props.button.setButtonTitle('fileManager', multiLang && multiLang.get('201102HKD-0009') + ' ' + lists + ' ');//'附件'
        })
    }

    renderErrorCenterState () {
        const { props } = this
        const { socket } = props;
        const status = props.form.getFormItemsValue('head', 'saga_status')
        if (!status || status.value !== '1') return null;
        
        this.props.button.toggleErrorStatus('head',{
            isError: true
        })

        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: 'head',
            billtype: props.form.getFormItemsValue('head', 'saga_status').value,
            billpkname: 'pk_jkbx',
            dataSource: 'erm.expenseaccount.repaymentExt.card'
        }
        return props.socket.connectMesg(param)
    }
    toggleAuditSideBar(fromBtn) {
        //判断是否是提交 按钮或者保存提交按钮
        fromBtn = fromBtn||window.presetVar.fromBtn
       
        
        let param = {};
        param.pk_group = this.getFormHeadValueByKey('pk_group'); // "集团pk"
        param.billtypecode = this.getFormHeadValueByKey('pk_billtype'); // "单据类型code" 
        param.tradetypecode = this.getFormHeadValueByKey('djlxbm'); // " 交易类型code"
        param.billid = this.getFormHeadValueByKey('pk_jkbx'); // "单据主键pk"
        param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        param.iscreate = "Y"   // 注意应该是制单首次保存传Y,浏览态去掉这个参数！！！是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入 做初始化 智能审批
        param.isEdit = true;
        
        // param.pk_group = "0001A510000000000NKA"; // "集团pk"
        // param.billtypecode = "267X"; // "单据类型code" 
        // param.tradetypecode = "267X"; // " 交易类型code"
        // param.billid = "1001A510000000003V27"; // "单据主键pk"
        // param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        // param.iscreate =  "Y"  // 是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入
        // param.isEdit = true; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        console.log('param111111111111111111111',param,this.props.getUrlParam("status"),this.props.getUrlParam("scene"))
        if(!param.billid){
            return
        }
        const isfromczh = this.props.getUrlParam("isfromczh")

        //展示后的回调
        this.auditSidebar.showSidebar(param,null,()=>{
            // this.auditSidebar.refreshSidebar()
            setTimeout(()=>{
                const auditSidebarObj = this.auditSidebar.getSidebarStatistical()
                console.log('1111111',auditSidebarObj)
                const {pointTree} = auditSidebarObj
                if(!pointTree.length){
                    this.setState({
                        showAuditSidebar:false
                    })
                    window.presetVar.auditCanSave = 0
                    return
                }
                this.setState({
                    showAuditSidebar:true
                })

                for(let i=0;i<pointTree.length;i++){
                    const leaf = pointTree[i]
                    if(leaf.children&&leaf.children.length){
                        if(leaf.children.some(item=>item.ispass==='N')){
                            window.presetVar.auditCanSave = 3 //目前需求只要有不通过的就提示风险
                            //1 严格控制 2风险提示
                            // if(leaf.children.some(item=>item.values.controltype=='1')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 1
                            //     break
                            // }else if(leaf.children.some(item=>item.values.controltype=='2')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 2
                            //     break
                            // }
                        }else{
                            window.presetVar.auditCanSave = 0
                        }
                    }
                }
                
                //展示风险弹窗
                if((fromBtn==='saveSubmit'||isfromczh)&&this.props.getUrlParam("status")==='browse'&&window.presetVar.auditCanSave>0){
                    let multiLang = this.props.MutiInit.getIntl(2011);
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0016'),
                        content: multiLang && multiLang.get('201102BCLF-0062'),
                        cancelBtnName:'收回',
                        beSureBtnClick: ()=>{
                            window.presetVar.auditCanSave = 0
                            
                        },
                        cancelBtnClick: () => {
                            pageButtonClick.call(this)[pageButton.billRecall]();
                            
                        }
                    })   
                }
            })
            
        })
        
    }
    getFormHeadValueByKey(key) { // 根据 form 获取 head 中的值
        return this.props.form.getFormItemsValue("head", key).value || '';
    }
    render() {
        let {modal,DragWidthCom} = this.props;
        let {createModal} = modal;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let btnModalConfig = {
            [pageButton.pageDel]: {
                // "2011-0004": "删除",
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005'),
            },
            [pageButton.billInvalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010'),
                beSureBtnClick: this.billInvalid.bind(this)
            }
        }
        let status = this.props.getUrlParam("status");
        let scene = this.props.getUrlParam("scene");
        let { showUploader,target,djzt,showAuditSidebar } = this.state;
        return (
            <div className='billWrapper'>
                {this.renderErrorCenterState()}
                <DragWidthCom
                    leftDom={
                        <BillStyle
                            {...this.props}
                        >
                            <BillHead
                                refreshButtonEvent={refreshButtonClick.bind(this)}
                                title={this.state.transtype_name}
                            >
                                <ButtonGroup
                                    areaId="head"
                                    buttonEvent={pageButtonClick.bind(this)}
                                    modalConfig={btnModalConfig}
                                    sagasButtonVisible={true}
                                />
                                <Form
                                    areaId="head"
                                    onAfterEvent={afterEvent.bind(this)} />

                            </BillHead>

                            <BillBody>

                                <CardTableGroup
                                    invisibleTables={[window.presetVar.body.body2]}
                                    excludeTableAreaId={null}
                                    totalItemCode="cjkybje"
                                    modelSave={pageButtonClick.bind(this, this.props, 'pageSave')}
                                    onBeforeEvent={beforeEvent.bind(this)}
                                    onAfterEvent={afterEvent.bind(this)}
                                >
                                    <MultiButtonGroup buttonEvent={tableButtonClick.bind(this)} />
                                </CardTableGroup>

                            </BillBody>

                        </BillStyle>
                    }
                    rightDom={
                        this.auditSidebar.createComponent()
                    }
                    aside="right"
                    defLeftWid={showAuditSidebar && djzt !== '0' && status === 'browse' && (scene !== 'sscermlink' && scene !== "linksce" && scene !== "lc" && scene !== "approve" && scene !== "approvesce" && scene !== 'zycl')
                        ? "20%" : '0%'}
                >
                </DragWidthCom>
           
   
        {/* 联查借款单 */}
        <LinkQueryJkbxModel
            show={this.state.showLinkQueryJkbxModel}
            linkData={this.state.linkData}
            close={() => this.setState({showLinkQueryJkbxModel: false})}
            tradetype={window.presetVar.tradetype}
            openBillId={this.state.billId}
            {...this.props}
        />

                <div>
                    {showUploader && < NCUploader
                        disableButton={this.state.uploaderBtnDisable}
                        billId={ this.state.billId }
                        targrt={target}
                        onHide={ this.onHideUploader.bind(this) }
                        customize={{'pk_billtypecode':this.props.getUrlParam('tradetype'), "djdl":"hk"}}
						customInterface={
                            {
							queryLeftTree:"/nccloud/erm/pub/ErmAttachmentTreeNodeQueryAction.do",
							queryAttachments: "/nccloud/erm/pub/ErmAttachmentQueryAction.do"
							}
						}
                        placement={'bottom'}
                    />
                    }
                </div>
                <div>
                <ApproveDetail
                    show={this.state.ShowApproveDetail}
                    close={this.closeApprove}
                    billtype={this.state.billtype}
                    billid={this.state.billId}
                />
            </div>
                <div>
                    <Inspection
                        show={ this.state.showLinkBudget }
                        sourceData = { this.state.sourceData }
                        cancel = { this.cancel.bind(this) }
                        affirm = { this.affirm.bind(this) }
                    />
                </div>
                <div>
                {/*"201102FYYT-0003": "指派",*/}
                {this.state.compositedisplay ? <ApprovalTrans
                    title= {multiLang && multiLang.get('201102FYYT-0003')}
                    data={this.state.compositedata}
                    display={this.state.compositedisplay}
                    getResult={this.getAssginUser}
                    cancel={this.turnOff.bind(this)}
                    /> : ""}
                </div>
            </div>
        )
    }
}

repaymentBillCard = createPage({
    mutiLangCode: '2011',
    billinfo:{
        billtype: 'card',  //虽然后台是一主多子数据结构，但是配置成extCard，编辑后请求公式验证会报错。因为会根据实际展现的表体数量来判断是一主多子还是一主一子。
        pagecode: '201102HKD_card_002', 
        headcode: 'head',
        bodycode: 'er_bxcontrast'
    },
    orderOfHotKey: ['er_bxcontrast']
})(repaymentBillCard);

export default repaymentBillCard;